/**
 * Created by zlj on 2016/12/8.
 */
var $ = require('jquery');
require('easyui');
var $alert = require("libs/alert");
var $confirm = require("libs/confirm");
var $validate = require("js-path/OneErrorPlaceFormValidate");
var isSale = require('libs/user-type').isSale;
$(function () {
    $(window).resize(function () {
        var $this = $(this);
        $('#goods_check_table').datagrid("resize",{
            width: 'auto',
            height: $this.height()
        });
    });
    $validate.validator(
        {form:"#check-sumbit",button:"#checkSubmit"},
        {
            declareName:{required:function (element) {
                return $('#check-sumbit input[name=checkReult]:checked').val() == 'Y';
            }},
            exportGoodsTax:{number:true},
            hsCode:{required:function (element) {
                return $('#check-sumbit input[name=checkReult]:checked').val() == 'Y';
            },digits:true}},
        {
            declareName:{required:'请按要求填写'},
            exportGoodsTax:{number:'请按要求填写'},
            hsCode:{required:'请按要求填写',digits:'请按要求填写'}
        },
        function () {
            var data = $('#check-sumbit').serializeObject();
            return data;
        },
        function (result) {
            if(result.code =='200'){
                $("#goodsinfo").modal("hide");
                $("#goodsinfoDetail").modal("hide");
                $("#goods_check_table").datagrid("reload");
            }else{
                $alert(result.message);
            }
        }
    );
    tbaleinit();
    comboxInit('api/v1/p/mms/area/query',{'level':'1'}
        ,$("#importCountryId"));
    $('#tb a[name=search]').on('click',function () {
        $('#goods_check_table').datagrid('load',{
            hasBattery:$('#tb input[name=hasBattery]').val(),
            entId:$('#tb input[name=entId]').val(),
            code:$('#tb input[name=code]').val(),
            chName:$('#tb input[name=chName]').val(),
            sendAuditSts:$('#tb input[name=sendAuditSts]').val(),
            importCountryId:$('#tb input[name=importCountryId]').val()
        })
    });

    $('#checkNewGoods').on('click',function () {
        var rows = $("#goods_check_table").datagrid("getSelections");
        if(rows.length == 0){
            $alert('请至少选择一个商品进行审核');
        }else{
            var data = {};
            data["isNew"] = 'Y';
            var ids = [];
            for (var i = 0 ;i<rows.length ;i++){
                if(rows[i].sendAuditSts != 'A'){
                    ids.push({id:rows[i].id});
                }
            }
            data["ids"] = ids;
            opt('api/v1/p/mms/goods/check/checkGoods',data,function (result) {
                $alert(result.message);
                $("#goods_check_table").datagrid("reload");
            })
        }
    });

    $('body').on('click','a[name=audi]',function () {
        var rowsData =  $('#goods_check_table').datagrid('getRows');
        var id = rowsData[$(this).attr('row')].id;
        loadGoods(id,"audi");
    });

    $('body').on('click','a[name=detail]',function () {
        var rowsData =  $('#goods_check_table').datagrid('getRows');
        var id = rowsData[$(this).attr('row')].id;
        loadGoods(id,"detail");
    });

    //2017-4-18
    $('#checkSubmit').on('click',function () {
        // $('#check-sumbit').attr('action','api/v1/p/mms/goods/check/checkGood');
        if($('#newCheckReult input[name=newCheckReult]:checked').val() == 'N' && $('#newareatext').val() == ''){
            $alert('新品审核失败原因不能为空!');
            return;
        }
        if($('#oldcheck input[name=checkReult]:checked').val() == 'N' && $('#areatext').val() == ''){
            $alert('审核失败原因不能为空!');
            return;
        } else {
            $('#check-sumbit').submit();
        }
    });
    $("#check-sumbit input[name=newCheckReult]").on("change",function () {
        if(this.value =='Y'){
            $('#newareatext').hide();
            $('#oldcheck').hide();
        }else{
            $('#newareatext').show();
            $('#oldcheck').show();
            $("#oldcheck input[name=checkReult]").get(0).checked=true;
            $('#areatext').hide();
        }
    });
    $("#oldcheck input[name=checkReult]").on("change",function () {
        if(this.value == 'Y'){
            $('#areatext').hide();
        }else {
            $('#areatext').show();
        }
    });
    $("body").on("click",'a[name=picture]',function () {
        var img = "<img src='"+$(this).data('path')+"'/>";
        $(this).parents('table').siblings('div').html(img);
    });
    $("#goodsinfo").on("hidden.bs.modal",function () {
        $(this).find(".tab-content .big-img").empty();
        $('#goodsinfo .big-img img').attr('src','');
        $('#goodsinfo .min-img').empty();
        $('#modal_title1').empty();
        $('#id').val('');
        var $spans = $('#goodsinfo .iteam span');
        $spans.empty();
        $("#check-sumbit textarea").empty();
        $("#check-sumbit input[type=text]").val('');
        $("#check-sumbit input[name='newCheckReult']").get(0).checked=true;
        $("#check-sumbit input[name='checkReult']").get(0).checked=true;
    });
    $("#goodsinfoDetail").on("hidden.bs.modal",function () {
        $(this).find(".tab-content .big-img").empty();
        $('#goodsinfoDetail .big-img img').attr('src','');
        $('#goodsinfoDetail .min-img').empty();
        $('#modal_title2').empty();
        var $spans = $('#goodsinfoDetail .iteam span');
        $spans.empty();
        $("#new_goods_detail textarea").empty();
        $("#new_goods_detail input[type=text]").val('');
        $("#new_goods_detail input[name='newCheckReult']").get(0).checked=true;
        $("#new_goods_detail input[name='checkReult']").get(0).checked=true;
    });
});

function tbaleinit() {
   $('#goods_check_table').datagrid({
       url:'api/v1/p/mms/goods/check/list?type=Y',
       border : false,
       height:$(window).height(),
       pagination : true,
       idField : 'id',
       pageSize : 20,
       pageList : [ 20, 50,  100 ],
       checkOnSelect : false,//单击选中
       emptyMsg : "暂无数据",
       selectOnCheck : true,
       rownumbers:true,
       frozenColumns:[[{
           field : 'id',
           checkbox:true
       }]],
       columns:[[
           {
               field:'entName',
               title:'客户名称',
               width:fixWidth(0.18),
               sortable:true,
               formatter:function (value,row,index) {
                   return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
               }
           },{
               field:'code',
               title:'商品编码',
               width:fixWidth(0.12),
               sortable:true,
               formatter:function (value,row,index) {
                   return '<a href="javascript:;" class="ellipsis" name="detail" row="'+index+'"><i class="glyphicon"></i>'+value+'</a>';
               }
           },
           {
               field:'chName',
               title:'商品中文名称',
               width:fixWidth(0.12),
               sortable:true,
               formatter:function (value,row,index) {
                   return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
               }
           },{
               field:'hasBattery',
               title:'是否带电',
               width:fixWidth(0.07),
               sortable:true,
               formatter:function (value,row,index) {
                   return 'Y'==value?'是':'否';
               }
           },{
               field:'detailWebsite',
               title:'网址',
               width:fixWidth(0.2),
               sortable:true,
               formatter:function (value,row,index) {
                   return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
               }
           },{
               field:'lastUpdateDt',
               title:'提交时间',
               width:fixWidth(0.1),
               sortable:true,
               formatter:function (value,row,index) {
                   return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
               }
           },{
               field:'sendAuditSts',
               title:'审核状态',
               width:fixWidth(0.07),
               sortable:true,
               formatter:function (value,row,index) {
                   if(value == 'U'){
                       return '已提交';
                   }else if(value=='P'){
                       return '审核通过';
                   }else if(value == 'R'){
                       return '审核失败';
                   }
               }
           },{
               field:'opt',
               title:'操作',
               hidden:isSale,
               width:fixWidth(0.05),
               formatter:function (value,row,index) {
                  switch (row.sendAuditSts){
                      case 'U':
                          return '<a href="javascript:;" name="audi" row="'+index+'"><i class="glyphicon glyphicon-pencil"></i>审核</a>';
                      default : return '';
                  }
               }
           }
       ]],
       loadFilter:function(data){
           if(data.code!='200'){
               $alert(data.message);
               return data.data;
           }
           return data.data;
       },
       onClickRow:function (index,data) {
           var $row = $("#datagrid-row-r1-1-"+index).find("input[type=checkbox]");
           if(!$row.prop("checked")){
               $(this).datagrid('unselectRow', index);
           }else{
               $(this).datagrid('selectRow', index);
           }
       },
       toolbar:"#tb"
   });
    $("#ft").show();
}

function fixWidth(percent)
{
    return (document.body.clientWidth - 5) * percent ;
}
//opt 操作 callback回调函数
function opt(url,data,callback) {
    $.ajax({
        url:url,
        type:'post',
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        dataType:'json',
        success:function (result) {
            callback(result);
        },
        error:function (e) {
            console.error('接口：'+url+'获取失败');
        }
    })
}
//load goods
function loadGoods(id,type) {
    $.ajax({
        url:'api/v1/p/mms/goods/check/load',
        type:'post',
        data:{
            id:id
        },
        dataType:'json',
        success:function (result) {
             if(result.code == 200){
                 appendData(result.data,type);
                 if(type == "audi"){
                     $('#goodsinfo').modal('show');
                 }else if(type == "detail"){
                     $('#goodsinfoDetail').modal('show');
                 }
             }else{
                 $alert(result.message);
             }
        },
        error:function (e) {
            console.error('url: api/v1/p/mms/goods/check/load 接口失败');
        }
    })
}
//append data
function appendData(data,type) {
    $('#id').val(data.id);
    var spans = '';
    $.each(data.pics,function (index,obj) {
        if(index == 0){
            if(type == "audi"){
                $('#goodsinfo div.big-img img').attr('src',obj.filePath);
            }else if(type == "detail"){
                $('#goodsinfoDetail div.big-img img').attr('src',obj.filePath);
            }
        }else{
            spans +="<span><img src='"+obj.filePath+"'></span>";
        }
    })
    if(type == "audi"){
        $('#modal_title1').html(data.chName);
        $('#goodsinfo div.min-img').append(spans);
        var $spans = $('#goodsinfo div.iteam span');
        var table = $('#goodsinfo #impcountries');
        var table2 = $('#goodsinfo #exceptions');
        var picture = $('#check .big-img');
    }else if(type == "detail"){
        $('#modal_title2').html(data.chName);
        $('#goodsinfoDetail div.min-img').append(spans);
        var $spans = $('#goodsinfoDetail div.iteam span');
        var table = $('#goodsinfoDetail #impcountries');
        var table2 = $('#goodsinfoDetail #exceptions');
        var picture = $('#checkDetail .big-img');
    }

    $($spans[0]).html(data.chName);
    $($spans[1]).html(data.enName);
    $($spans[2]).html(data.code);
    $($spans[3]).html(data.spec);
    $($spans[4]).html(data.model);
    $($spans[5]).html(data.brand);

    var batteryType='';
    if(data.batteryType == 'alkaline'){
        batteryType = '碱性电池';
    }else if(data.batteryType == 'lithium'){
        batteryType = '锂电池';
    }else{
        batteryType = '不带电';
    }
    $($spans[6]).html(batteryType);

    var keywords ;
    if(data.keyword.length > 0){
        keywords = data.keyword.join(',');
    }else {
        keywords = '';
    }
    $($spans[7]).html(keywords);

    $($spans[8]).html(data.regGrossWeight);
    $($spans[9]).html(data.regLength);
    $($spans[10]).html(data.regWidth);
    $($spans[11]).html(data.regHeight);
    $($spans[12]).html(data.factGrossWeight);
    $($spans[13]).html(data.factLength);
    $($spans[14]).html(data.factWidth);
    $($spans[15]).html(data.factHigh);

    $($spans[16]).html(data.hsCode);
    $($spans[17]).html(data.manageType);
    $($spans[18]).html(data.exportGoodsTax);

    $($spans[19]).html(data.declaredPrice);

    $($spans[20]).html('');

    $($spans[21]).html(data.deliveryCycle);
    $($spans[22]).html(data.detailWebsite);
    $($spans[22]).parent('a').attr('href',data.detailWebsite);
    $($spans[23]).html(data.summary);
    countryTableInit(table,data.impCountries);
    exceptionsTableInit(table2,data.boxExpInfoVOS);
    newPicsInit(picture,data.newPics);
    if(type == "audi"){
        $("#newareatext").html(data.sendRejectReason);
        $("#areatext").html(data.orderRejectReason)
        if(data.sendAuditSts == 'R'){
            $("#newCheckReult input[name='newCheckReult']").get(1).checked=true;
            $("#oldcheck input[name='checkReult']").get(0).checked=true;
            $('#areatext').hide();
        }else if(data.sendAuditSts == 'U'){
            $("#newCheckReult input[name='newCheckReult']").get(0).checked=true;
            $('#newareatext').hide();
            $('#oldcheck').hide();
        }
        //2017-3-10
        $("#check-sumbit input[name=hsCode]").val(data.hsCode);
        $("#check-sumbit input[name=exportGoodsTax]").val(data.exportGoodsTax);
        $("#check-sumbit input[name=declareName]").val(data.declareName);
        $("#check-sumbit input[name=declareFactor]").val(data.declareFactor);
    }else if(type == "detail"){
        $("#newareatextDetail").html(data.sendRejectReason);
        $("#areatextDetail").html(data.orderRejectReason)

        if(data.sendAuditSts == 'R'){
            $("#newareatextDetail").show();
            $("#newCheckReultDetail input[name='newCheckReult']").get(2).checked=true;
            if(data.orderAuditSts == 'C'){
                $("#oldcheckDetail input[name='checkReult']").get(0).checked=true;
                $('#areatextDetail').hide();
            }else if(data.orderAuditSts == 'P'){
                $("#oldcheckDetail input[name='checkReult']").get(1).checked=true;
                $('#areatextDetail').hide();
            }else if(data.orderAuditSts == 'R'){
                $("#oldcheckDetail input[name='checkReult']").get(2).checked=true;
                $('#areatextDetail').show();
            }
        }else if(data.sendAuditSts == 'U'){
            $("#newCheckReultDetail input[name='newCheckReult']").get(0).checked=true;
            $('#newareatextDetail').hide();
            $('#oldcheckDetail').hide();
            if(data.orderAuditSts == 'C'){
                $("#oldcheckDetail input[name='checkReult']").get(0).checked=true;
                $('#areatextDetail').hide();
            }else if(data.orderAuditSts == 'P'){
                $("#oldcheckDetail input[name='checkReult']").get(1).checked=true;
                $('#areatextDetail').hide();
            }else if(data.orderAuditSts == 'R'){
                $("#oldcheckDetail input[name='checkReult']").get(2).checked=true;
                $('#areatextDetail').show();
            }
        }else if(data.sendAuditSts == 'P'){
            $("#newCheckReultDetail input[name='newCheckReult']").get(1).checked=true
        }
        //2017-3-10
        $("#new_goods_detail input[name=hsCode]").val(data.hsCode);
        $("#new_goods_detail input[name=exportGoodsTax]").val(data.exportGoodsTax);
        $("#new_goods_detail input[name=declareName]").val(data.declareName);
        $("#new_goods_detail input[name=declareFactor]").val(data.declareFactor);
    }
}
//添加参数
function comboxInit(url,data,$select) {
    $select.combobox({
        url:url,
        valueField:'id',
        textField:'name',
        queryParams:data,
        loadFilter:function(result){
            if(result.code=='200'){
                result.data.unshift({id:'',name:'全部'});
                return result.data;
            }
        }
    })
}
function countryTableInit(table,data) {
    var trs = '';
    $.each(data,function (index,obj) {
        trs += "<tr><td>"+obj.country+"</td><td>"+obj.importGoodsTax+"</td><td>"+obj.importGoodsPrice+"</td><td>"+obj.currency+"</td></tr>";
    });
    $(table).find('tbody').html(trs);
}
function exceptionsTableInit(table,data) {
    var trs = '';
    $.each(data,function (index,obj) {
        trs += "<tr><td>"+obj.boxCode+"</td><td>"+obj.code+"</td><td>"+obj.reason
            +"</td><td><a href='javascript:;' name='picture' data-path='"+obj.filePath+"'>查看</a></td></tr>";
    });
    $(table).find('tbody').html(trs);
}
function newPicsInit(picture,data) {
    var imgs = '';
    $.each(data,function (index,obj) {
        imgs += "<img src='"+obj.filePath+"'/>";
    });
    $(picture).html(imgs);
}
